package com.i2works.smartluolong.web.controller.common;

import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.AppConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.common.DateUtils;
import com.i2works.smartluolong.utils.common.SmsUtil;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.redis.RedisSessionDAO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/1/29 16:52
 */
@RestController
@RequestMapping("/common/sms")
public class SmsController {

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private RedisSessionDAO redisSessionDAO;

    /**
     * 发送验证码
     */
    @PostMapping("/send")
    public Result send(@RequestParam(value = "phone", required = false) String phone) {
        if (StringUtils.isBlank(phone)) {
            return R.error(MsgEnum.ACCESS_PHONE_NULL.getMsg());
        }
        String exisKey = String.format("SMS_TAG_%s", phone);
        if (redisSessionDAO.exists(exisKey)) {
            return R.error(MsgEnum.SMS_CODE_REPEAT.getMsg());
        } else {
            redisSessionDAO.set(exisKey, DateUtils.get(), 60L);
            return smsUtil.captcha(AppConstant.ALIYUN_SMS_TEMPLATECODE, Lists.newArrayList(phone));
        }
    }


    /**
     * 校验短信
     */
    @PostMapping("/check")
    public Object check(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "phone", required = false) String phone, @RequestParam(value = "status", required = false) Boolean status) {
        Result contrast = smsUtil.contrast(phone, code);
        return status ? contrast.getSuccess() : contrast;

    }


}
